package com.kylin.java;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str = "我是UDP方式发送的导弹";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        //创建数据包
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 9090);
        //发送数据包
        socket.send(packet);
        //关闭资源
        socket.close();

    }
    //接收端
    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(9090);
        byte[] buffer = new byte[100];
        //创建数据包
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        //接受数据包
        socket.receive(packet);
        //打印数据
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        //关闭资源
        socket.close();
    }
}

